<template>
  <div class="login-page">
    <div class="login-header">
      <Image :src="Logo" fit="contain"
        width="120"></Image>
    </div>

    <Form ref="form" class="form">
      <SwitchSwiper class="mx-auto"
        v-model="userStore.loginType" />
      <Field v-model="params.phone" name="phone"
        placeholder="请输入手机号" :rules="[
          { required: true, message: '请填写手机号' },
          // { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误' }
        ]" class="field" />
      <Field v-model="params.password"
        v-if="userStore.loginType === LoginType.LOGIN_BY_PASS"
        :type="passwordType" name="password"
        @click-right-icon="showPassword = !showPassword"
        :right-icon="rightIcon"
        placeholder="请输入密码" :rules="[
          { required: true, message: '请填写密码' },
          // {
          //   pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/,
          //   message: '密码必须包含字母和数字，长度在8-16之间'
          // }
        ]" class="field" />
      <Field v-model="params.code" name="code"
        v-if="userStore.loginType === LoginType.REGISTER_BY_CODE"
        placeholder="请输入6位验证码" class="field"
        :rules="[{ required: true, message: '请输入验证码' }]">
        <template #button>
          <Button size="mini" type="primary"
            :loading="captChaCodeLoading"
            :disabled="!showSendCode" block
            @click="sendSmsCode">
            {{ countdown > 0 ? `${countdown}s后重发` : '验证码' }}
          </Button>
        </template>
      </Field>
    </Form>
    <div class="actions-button">
      <div class="extra-actions">
        <a @click="gotoRegister">立即注册</a>
        <!-- <a @click="gotoForget">忘记密码？</a> -->
      </div>
      <Button round block type="primary"
        :loading="userStore.loading" @click="handleLogin">
        立即登录
      </Button>
      <Checkbox v-model="checked" label-disabled>
        <span style="font-size: 12px;">
          我已阅读并同意
          <span
            style="color: var(--van-primary-color);"
            @click="handleClick('UserService')">
            《用户服务协议》
          </span>和
          <span
            style="color: var(--van-primary-color)"
            @click="handleClick('PolicyProtocol')">
            《隐私政策》
          </span>
        </span>
      </Checkbox>
    </div>
  </div>
  <Verify @success="success" mode="pop"
    captchaType="clickWord"
    :imgSize="{ width: '330px', height: '155px' }"
    ref="verify" />
</template>

<script setup lang="ts">
import {
  Button, Checkbox, Field, Form,
  Image,
  showFailToast,
  showToast,
} from 'vant';
import { computed, ref } from 'vue';
import { useRouter } from 'vue-router';

import { getCaptchaCode } from '@/api';
import Logo from '@/assets/images/kuaihs.png';
import useUserStore from '@/stores/user.store';

import SwitchSwiper from '../components/SwitchSwiper.vue';
import Verify from '../components/verifition/Verify.vue';
import { LoginType } from '../const';
import LoginInstance from '../models/LoginInstance';

const router = useRouter();
const userStore = useUserStore();

const verify = ref({} as any);
const isVerify = ref(false);

const loading = ref(false);
const checked = ref(false);
const form = ref({
  validate: () => Promise.resolve(),
});
const params = ref<LoginInstance>(new LoginInstance());

const handleVerify = () => {
  verify.value.show();
};

const fetchLogin = async () => {
  await form.value.validate();
  await userStore.login(params.value);
};

const handleLogin = async () => {
  try {
    if (!checked.value) {
      showFailToast('请先阅读并同意《用户服务协议》和《隐私政策》');
      return;
    }
    loading.value = true;
    await form.value?.validate();
    fetchLogin();
  } catch (error) {
    //
  } finally {
    loading.value = false;
  }
};

const countdown = ref(0);
const captChaCodeLoading = ref(false);
const showSendCode = computed(() => /^1[3-9]\d{9}$/.test(params.value.phone) && countdown.value === 0);
const sendSmsCode = async () => {
  if (!showSendCode.value) return;
  if (!isVerify.value) {
    handleVerify();
    return;
  }
  try {
    captChaCodeLoading.value = true;
    const { data } = await getCaptchaCode(params.value);
    countdown.value = 60;
    const timer = setInterval(() => {
      countdown.value -= 1;
      if (countdown.value <= 0) clearInterval(timer);
    }, 1000);
    showToast(data.msg || '验证码已发送');
  } catch (error) {
    //
  } finally {
    captChaCodeLoading.value = false;
    isVerify.value = false;
  }
};

type TSucess = {
  captchaVerification: string
}

const success = async (param:TSucess) => {
  params.value.captchaVerification = param.captchaVerification;
  isVerify.value = true;
  sendSmsCode();
};

const gotoRegister = () => {
  router.replace({ name: 'RegisterPage' });
};

const handleClick = (name: string) => {
  router.replace({ name });
};

const showPassword = ref(false);
const rightIcon = computed(() => (showPassword.value ? 'eye-o' : 'closed-eye'));
const passwordType = computed(() => (showPassword.value ? 'text' : 'password'));
</script>

<style lang="less" scoped>
.login-page {
  height: 100%;
  padding: 40px 20px;

  .login-header {
    text-align: center;
    margin-bottom: 10px;

    h2 {
      font-size: 24px;
      margin: 10px 0;
    }

    p {
      font-size: 16px;
      opacity: 0.9;
    }
  }

  .form {
    width: 100%;

    .field {
      background: var(--van-gray-2);
      margin-bottom: 20px;
      border-radius: 50px;
    }
  }

  .actions-button {
    display: flex;
    flex-direction: column;
    gap: 10px;
    margin-top: 20px;

    .extra-actions {
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      color: var(--van-primary-color);
      padding: 0 20px;
    }
  }
}

.mx-auto {
  margin-left: auto;
  margin-right: auto
}
</style>
